package com.itheima.controller;

import com.itheima.pojo.Article;
import com.itheima.pojo.PageBean;
import com.itheima.pojo.Result;
import com.itheima.pojo.User;
import com.itheima.service.ArticleService;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    private ArticleService articleService;

    @Autowired
    private UserService userService;

    @PostMapping
    public Result add(@RequestBody @Validated(Article.Add.class) Article article){
        articleService.add(article);
        System.out.println("我是帅哥");
        System.out.println(article);
        return Result.success();
    }

    @GetMapping("/oneUserAticleList")
    public Result<PageBean<Article>> list(
            Integer pageNum,
            Integer pageSize,
            @RequestParam(required = false) Integer categoryId,
            @RequestParam(required = false) String state
    ){
        PageBean<Article> pb = articleService.list(pageNum,pageSize,categoryId,state);
        return Result.success(pb);
    }

    @GetMapping("/allArticleList")
    public Result<List<Article>> allArticleList(
            @RequestParam(required = false) Integer categoryId,
            @RequestParam(required = false) String title
    ){

        List<Article> articleList = articleService.allList(categoryId,title);
        List<User> allUserInfo = userService.getAllUserInfo();
        for (Article article:articleList){
            for (User user:allUserInfo){
                if (article.getCreateUser().equals(user.getId())){
                    article.setUsername(user.getNickname());
                    break;
                }
                article.setUsername("该用户已注销");
            }
        }
        return Result.success(articleList);
    }
    @GetMapping("/detail")
    public Result<Article> detail(Integer id){
        Article article = articleService.detail(id);
        return Result.success(article);
    }

    @PutMapping
    public Result update(@RequestBody @Validated(Article.Update.class) Article article){
        articleService.update(article);
        return Result.success();
    }

    @DeleteMapping
    public Result delete(Integer id){
        articleService.delete(id);
        return Result.success();
    }
}
